package com.saris.primego.common.handler;

import com.saris.primego.common.constant.MessageConstant;
import com.saris.primego.common.exception.BaseException;
import com.saris.primego.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
//把springboot版本降到3.12问题解决
@RestControllerAdvice(annotations = RestController.class)
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BaseException.class)
    public Result<String> exceptionHandler(BaseException exception) {
//        log.error("异常信息：{}", exception.getMessage());
        return Result.error(exception.getMessage());
    }

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException exception) {

        String message = exception.getMessage();

        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String userName = split[2];
            String msg = userName + MessageConstant.ALREADY_EXISTS;
//            log.error("异常信息：{}", msg);
            return Result.error(msg);
        } else {
//            log.error("异常信息：{}", MessageConstant.UNKNOWN_ERROR);
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }

}


